<template>
    <div class="friendcirclemat_container">
        <ZWGroup ref="ZWGroupRef" :group-id="groupId" :type="8" @submit="getFiles" />
        <div class="friendcirclemat_main">
            <ZwSearchForm row-num="2" :option="searchOption" @search="search" @reset="reset" />
            <ZwTable
                ref="tableRef"
                close-loading
                tab-h="initial"
                :option="tableOption"
                :row-key="getRowKey"
                :fetch-params="state.searchParams"
                :fetch-api="fetchApi()"
                @select-all="onSelectAll"
                @select="onSelect">
                <template #headerOperate>
                    <el-button :disabled="sectionIds.length == 0" @click="batchDel">批量删除</el-button>
                    <el-button type="primary" @click="createFriend">创作素材</el-button>
                </template>
            </ZwTable>
        </div>

        <!-- 删除弹框 -->
        <ZWDeletdialog ref="DeletdialogRef" @submit="del" />
        <!-- 预览抽屉层 -->
        <ZWDrawer ref="DrawerRef">
            <!-- <Friend :phoneFriend="phoneFriend" /> -->
            <div class="phonePreview">
                <PhonePreview
                    ref="phonePreviewRef"
                    :input-content-data="inputContentData"
                    :material-content-data="materialContentData" />
            </div>
        </ZWDrawer>
    </div>
</template>

<script setup lang="tsx">
import ZWGroup from '@/components/ZWGroup.vue';
import Upload from '../components/Upload.vue';
import ZWSelectTag from '@/components/ZWSelectTag.vue';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import ZWDrawer from '@/components/ZWDrawer.vue';
import Friend from './components/friend.vue';

import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import PhonePreview from '@/components/zw/phonePreview/friendCircle/materialPreview/index.vue';

import { ref, reactive, onMounted, computed, watch, nextTick } from 'vue';
import router from '@/router';
import { useRoute } from 'vue-router';
import { friendList, friendDel, friendDetail, batchContentDel } from '@/api/concreation';
import { getCreateList } from '@/api/common';
import { useStore } from '@/store';
import { IsNotEmpty, getSetionId, getVideoImage, initMaterialData, isTextBeyond } from '@/utils/utils';

import { deepCopy } from '@/utils/helper';
import { dividerProps, ElButton, ElMessage, ElPopover, ElBadge, ElImage, ElTooltip } from 'element-plus';

const store = useStore();
const SelectTagRef = ref(null);
const isContent = ref(true);
const DeletdialogRef = ref(null);
const ZWGroupRef = ref(null);
const SearchRef = ref(null);
const FormulaBarRef = ref(null);
const DrawerRef = ref(null);
const PaginationRef = ref(null);
const selectGroupId = ref(0);
const route = useRoute();
const sectionIds = ref([]);
const groupId = ref<number | string>(Number.isNaN(route.query?.groupId) ? 'all' : route.query?.groupId);

const phonePreviewRef = ref<HTMLElement | null>();
const inputContentData = ref<string>(''); //  用户存放回显数据  欢迎语输入框
const materialContentData = ref<Array<any>>([]);

const tableRef = ref(null);
const defaultParams = reactive({
    content: '',
    group_id: groupId.value || 0,
    created_uid: '',
    creat_time: []
});
const state = reactive({
    searchParams: deepCopy(defaultParams),
    searchHeight: '112px'
});
const searchOption = computed(() => {
    return [
        {
            label: '内容搜索',
            name: 'content',
            value: '',
            type: 'input',
            placeholder: '请输入内容进行查找'
        },
        {
            label: '创建者',
            name: 'created_uid',
            value: [],
            multiple: true,
            type: 'select',
            filterable: true,
            placeholder: '全部',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getCreateList({}).then((res: any) => {
                        const targetArr = res.map((item: any) => {
                            item.name = `${item.name}  (${item.phone})`;
                            return item;
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '添加时间',
            name: 'creat_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间'
        }
    ];
});
const tableOption = [
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        prop: 'title',
        label: '标题',
        minWidth: 200,
        showOverflowTooltip: true
    },
    {
        label: '内容',
        minWidth: 300,
        render({ row }: any) {
            return (
                <>
                    <ElTooltip
                        disabled={contentDisabled.value}
                        content={row.content_text}
                        effect="dark"
                        placement="top-start">
                        <div onMouseenter={handleMouse} class="zw-text-ellipsis2" vShow={[0, 1, 2].includes(row.type)}>
                            {row.content_text}
                        </div>
                    </ElTooltip>
                    <div class="table_file_content" vShow={![0, 1, 2].includes(row.type)}>
                        <div class="content_l">
                            <div class="con_title">{row.mediaLinkInfo.link_title || row.mediaMiniInfo?.title}</div>
                            <div class="con_desc">{row.mediaLinkInfo.link_decs} </div>
                        </div>
                        <img
                            class="content_img"
                            src={
                                row.mediaLinkInfo.media_content_link?.cover_image_url ||
                                row.mediaLinkInfo?.link_share_image ||
                                row.mediaMiniInfo?.image_url
                            }
                            alt=""
                        />
                    </div>
                </>
            );
        }
    },
    {
        label: '图片',
        width: 150,
        render({ row }: any) {
            return (
                <>
                    <div vShow={row.type == 1} style="margin-top: 10px;">
                        <ElBadge
                            vShow={row.mediaFileInfo.length > 1}
                            value={row.mediaFileInfo.length}
                            max={99}
                            class="item_image">
                            <ElImage
                                class="img_icon"
                                src={row.mediaFileInfo[0]?.absolute_url}
                                preview-src-list={prevImgs(row.mediaFileInfo)}
                                preview-teleported={true}
                            />
                        </ElBadge>
                        <ElImage
                            vShow={row.mediaFileInfo.length <= 1}
                            class="img_icon"
                            src={row.mediaFileInfo[0]?.absolute_url}
                            preview-src-list={[row.mediaFileInfo[0]?.absolute_url]}
                            preview-teleported={true}
                        />
                    </div>
                    <div vShow={row.type != 1}>--</div>
                </>
            );
        }
    },
    {
        label: '视频',
        width: 200,
        render({ row }: any) {
            return (
                <>
                    <div vShow={row.type == 2 && row.mediaFileInfo.length > 0}>
                        <div class="video_box" onClick={() => downLoad(row.mediaFileInfo[0]?.absolute_url)}>
                            <img class="img_icon" src={getVideoImage(row.mediaFileInfo[0]?.absolute_url, 60, 60)} />
                            <img class="play_icon" src="@/assets/play.png" alt="" />
                        </div>
                    </div>
                    <div vShow={row.type != 2 && row.mediaFileInfo.length <= 0}>--</div>
                </>
            );
        }
    },
    {
        prop: 'user_name',
        label: '创建人',
        width: 150
    },
    {
        prop: 'created_at',
        label: '添加时间',
        width: 180
    },
    {
        prop: 'operate',
        label: '操作',
        fixed: 'right',
        width: 220,
        isOperate: true,
        renderOperate({ row }: any) {
            return sopBtnList.map((item: any, index: number) => {
                return (
                    <ElButton size="small" v-auth={item.authCode} onClick={() => item.click(row, item.id)}>
                        {item.val}
                    </ElButton>
                );
            });
        }
    }
];

const getRowKey = (row: any) => {
    return row.id;
};

const search = (data: any) => {
    tableRef.value?.clearSelection();
    state.searchParams = deepCopy({ ...defaultParams, ...data, group_id: groupId.value });
};
const reset = (v: any) => {
    tableRef.value?.clearSelection();
    state.searchParams = deepCopy({ ...defaultParams, group_id: groupId.value });
};

/**
 * 内容区，是否溢出展示tooltip
 */
const contentDisabled = ref(true);
/**
 * 鼠标移动table
 * @param e
 */
const handleMouse = (e: any) => {
    contentDisabled.value = isTextBeyond(e, 2);
};

// 获取表格高度
const getTableH = () => {
    nextTick(() => {
        tableRef.value.getTableH();
    });
};
const fetchApi = () => {
    // 获取文件列表
    getTableH();
    return friendList;
};
const createFriend = () => {
    router.push(`/content/friendcirclemat/createFriend?groupId=${groupId.value === 'all' ? 0 : groupId.value}`);
};
// 选中表格 checkbox
const onSelect = (selection: any) => {
    sectionIds.value = getSetionId('id', selection);
};
// 全选
const onSelectAll = (selection: any) => {
    sectionIds.value = getSetionId('id', selection);
};
//预览
const downLoad = (url: any) => {
    window.open(url);
};
// 分组
// 选中复选框
const table = computed(() => {
    return store.getters['table'];
});
//编辑
const Edit = (val: any) => {
    router.push(`/content/friendcirclemat/createFriend?id=${val.id}&type=edit`);
};
//是否批量
const IsBatch = ref(true);
const phoneFriend = ref({});
const prevImgs = (data: any) => {
    return getSetionId('absolute_url', data);
};
// 预览
const preInfo = async (val: any) => {
    try {
        const res: any = await friendDetail({
            media_moment_id: val.id
        });

        inputContentData.value = res.welcome_info.welcome_text;
        materialContentData.value = initMaterialData(res.welcome_info.welcome_material);

        DrawerRef.value.drawer = true;
        DrawerRef.value.width = 430;
        DrawerRef.value.title = res.title;
        DrawerRef.value.isShow = false;
        phoneFriend.value = {
            name: val.user_name,
            content: res.content_text,
            title: res.title,
            type: res.type,
            create_timer: res.created_at
        };
        // 图片
        if (res.type == 1) {
            phoneFriend.value.list = res.image;
        } else if (res.type == 2) {
            //视频
            phoneFriend.value.list = [res.video];
        } else if (res.type == 11) {
            phoneFriend.value.list = [
                {
                    title: res.mini.link_title,
                    cover_image_url: res.mini.link_share_image,
                    content: res.mini.link_decs || res.link.link_desc,
                    url: res.mini.link_url
                }
            ];
        } else {
            // 链接
            phoneFriend.value.list = [
                {
                    title: res.link.link_title,
                    cover_image_url: res.link.link_share_image,
                    content: res.link.link_decs || res.link.link_desc,
                    url: res.link.link_url
                }
            ];
        }
    } catch (e) {}
};
// 删除
const remove = (val: any) => {
    sectionIds.value = [val.id];
    IsBatch.value = false;
    DeletdialogRef.value.appDialog.visible = true;
};
// 批量删除
const batchDel = () => {
    IsBatch.value = true;
    DeletdialogRef.value.appDialog.visible = true;
};
// 删除确认
const del = async () => {
    try {
        store.commit('user/setApiList', [
            '/scrm-api/console/media/moment/destroy',
            '/scrm-api/console/tenant/group/getLists',
            '/scrm-api/console/media/moment/getList'
        ]);
        //  删除
        await friendDel({
            media_moment_id: sectionIds.value
        });
        ElMessage.success(`${IsBatch.value ? '批量' : ''}删除成功`);
        DeletdialogRef.value.appDialog.visible = false;
        tableRef.value?.clearSelection();
        search(state.searchParams);
        // store.dispatch('table', {
        //   tableData: [],
        //   tableAll: false
        // })
        ZWGroupRef.value.getGroup();
        ZWGroupRef.value.setCurrentSelectId({ id: groupId.value });
    } catch (e) {}
};
const sopBtnList = reactive([
    { id: 0, val: '预览', click: preInfo, authCode: 'CREATION_FD' },
    { id: 1, val: '编辑', click: Edit, authCode: 'EDIT_FD' },
    { id: 2, val: '删除', click: remove, authCode: 'DEL_FD' }
]);
const getFiles = (data?: any) => {
    groupId.value = data?.id;
    defaultParams.group_id = data?.id;
    search({ ...defaultParams, ...state.searchParams });
    tableRef.value?.clearSelection();
};

onMounted(async () => {
    store.commit('user/setApiList', [
        '/scrm-api/console/tenant/group/getLists',
        '/scrm-api/console/media/moment/getList'
    ]);

    if (route.query?.groupId) {
        groupId.value = Number(route.query?.groupId);
        await ZWGroupRef.value.getGroup(8);
        await nextTick();
        ZWGroupRef.value.setCurrentSelectId({ id: groupId.value });
    }
    // if (groupId.value) {
    //     setTimeout(() => {
    //         // ZWGroupRef.value.changeGroup({ id: groupId.value });
    //     }, 50);
    // }

    // router.push({ query: {} });
});
watch(table, table => {
    sectionIds.value = getSetionId('id', table.tableData);
});
</script>

<style lang="scss" scoped>
.friendcirclemat_container {
    display: flex;

    .friendcirclemat_main {
        flex: 1;
        height: calc(100vh - 142px);
        padding: 24px;
        border: 1px solid #eaeaea;
        border-radius: 4px;
        box-sizing: border-box;
        background-color: #fff;
        display: flex;
        flex-direction: column;
        overflow: hidden;

        .zw-table {
            display: flex;
            flex-direction: column;
            flex: 1;
            overflow: hidden;

            :deep(.el-table) {
                flex: 1;

                .el-table__empty-block {
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                }
            }
        }
    }
}

.text_content {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
}

:deep(.table_file_content) {
    width: 270px;
    height: 70px;
    box-sizing: border-box;
    padding: 5px;
    background: #f9f9f9;
    border-radius: 1px;
    border: 1px solid #eaeaea;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .content_l {
        width: 190px;

        .con_title {
            font-size: 14px;
            font-family: STHeitiSC-Medium, STHeitiSC;
            font-weight: 500;
            color: #33302d;
            line-height: 14px;
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
            word-break: break-all;
            margin-bottom: 4px;
        }

        .con_desc {
            font-size: 12px;
            font-family: STHeitiSC-Light, STHeitiSC;
            font-weight: 300;
            color: #969696;
            line-height: 14px;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            line-clamp: 2;
            -webkit-box-orient: vertical;
        }
    }
}

:deep(.content_img) {
    width: 60px;
    height: 60px;
    border-radius: 2px;
}

:deep(.img_icon) {
    width: 60px;
    height: 60px;
    border-radius: 1px;
}

.video_box {
    position: relative;
    left: 50%;
    transform: translate(-50%);
    width: 60px;
    height: 60px;

    .play_icon {
        position: absolute;
        width: 26px;
        height: 26px;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
    }
}

.item_image {
    margin: 10px 0;
}

:deep .phonePreview {
    display: flex;
    align-items: center;
    justify-content: center;
    padding-top: 80px;
}
</style>
